package com.example.d3.character.compare;

import java.math.BigDecimal;
import java.math.MathContext;
import java.util.HashMap;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class StatAdapter extends BaseAdapter {
	private Context context;
	private String[] statKeys;
	
	private HashMap<String, Double> stats1 = new HashMap<String, Double>();
	private HashMap<String, Double> stats2 = new HashMap<String, Double>();
	
	private String hero1Name;
	private String hero2Name;
	
	public StatAdapter(Context context, HeroData hero1, HeroData hero2) {
		this.context = context;
		this.stats1 = hero1.getStats();
		this.statKeys = this.stats1.keySet().toArray(new String[this.stats1.size()]);
		this.hero1Name = hero1.name();
		
		if(hero2.isValid()){
			this.stats2 = hero2.getStats();
			this.hero2Name = hero2.name();
		}
	}
	
	public int getCount() {
		return stats1.size();
	}

	public Object getItem(int pos){
		return stats1.get(statKeys[pos]);
	}
	public Object getItem2(int pos){
		return stats2.get(statKeys[pos]);
	}
	
	public long getItemId(int pos){
		return pos;
	}
	
	public View getView(int pos, View convertView, ViewGroup viewGroup){
		String stat = statKeys[pos];
		Double val = (Double)getItem(pos), val2 = 0.0;
		Double deltaVal = 0.0;
		if(stats2.size() == stats1.size()){
			val2 = (Double)getItem2(pos);
			deltaVal = val - val2;
		}
		
		if(convertView == null) {
			LayoutInflater infl = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			convertView = infl.inflate(R.layout.stat_item, null);
		}
		
		((TextView)convertView.findViewById(R.id.stat)).setText(stat + ": ");
		String charStats = hero1Name + ": " + formatValue(val);
		
		if(stats2.size() == stats1.size()){
			charStats += " " + hero2Name + ": " + formatValue(val2);
		}
		
		((TextView)convertView.findViewById(R.id.statValue)).setText(charStats);
		if(deltaVal != 0.0){
			if(deltaVal < 0.0){
				//hide down arrow
				((ImageView)convertView.findViewById(R.id.img_arrow_down)).setVisibility(View.VISIBLE);
				((ImageView)convertView.findViewById(R.id.img_arrow_up)).setVisibility(View.INVISIBLE);
			} else {
				//show up arrow
				((ImageView)convertView.findViewById(R.id.img_arrow_up)).setVisibility(View.VISIBLE);
				((ImageView)convertView.findViewById(R.id.img_arrow_down)).setVisibility(View.INVISIBLE);
			}
			((TextView)convertView.findViewById(R.id.deltaValue)).setText(formatValue(deltaVal));
		}
		
		return convertView;
	}
	
	public String formatValue(Double value){
		BigDecimal bd = new BigDecimal(value);
		bd = bd.round(new MathContext(4));
		return bd.toString();
	}
}
